<template>
  <div ref="container" id="dispatchReportPage">
    <el-container style="width: 80%; margin: 0 auto">
      <el-header class="header-bg header-line-height">
        <div v-bind:class="{ half: evaluated }">
          <h1 class="header-title">{{ form.textName }}</h1>
          <el-select v-model="isAll" @change="handleSelectChange" style="margin-top: 10%; margin-left: 20%">
            <el-option v-for="d in reportTypeList" :value="d.id" :label="d.label" :key="d.id"></el-option>
          </el-select>
        </div>
        <div style="width: 50%; height: 100%; padding-top: 10%" v-if="evaluated">
          <div style="text-align: center">
            <h5>{{ columnName + ':' }}</h5>
            <h2>{{ evaluatedName }}</h2>
          </div>
          <div style="text-align: center">
            <h5>{{ columnName + '得分:' }}</h5>
            <h2 v-if="dataList.length > 0">{{ dataList[0].average }}</h2>
            <h2 v-else>0</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <template>
          <el-select v-if="evaluated" v-model="evaluated" @change="handleEvaluatedSelect" filterable>
            <el-option
              v-for="e in evaluatedList"
              :key="e.evaluated"
              :value="e.evaluated"
              :label="e.evaluatedName"
            ></el-option>
          </el-select>
          <h3 class="sub-title">综合测评</h3>
          <el-table :data="dataList" :header-cell-style="{ 'font-size': '16px' }" style="font-size: 16px" stripe>
            <el-table-column :label="columnName" prop="evaluatedName" align="left"></el-table-column>
            <el-table-column label="得分" prop="average" align="center" sortable></el-table-column>
            <el-table-column label="平均分" prop="totalAverage" align="center"></el-table-column>
            <el-table-column label="分值差" align="center">
              <template v-slot="scope">
                <span :class="scope.row.average - scope.row.totalAverage >= 0 ? 'green' : 'red'">
                  {{ (scope.row.average - scope.row.totalAverage) | numFilter }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="按题目平均" align="center">
              <template v-slot="scope">
                {{ (scope.row.average / detailList.length).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="详细报告" align="center" v-if="!evaluated">
              <template v-slot="scope">
                <el-link
                  type="primary"
                  :href="
                    '/project/form/statistics?activeTab=report&type=' +
                    type +
                    '&evaluated=' +
                    scope.row.evaluated +
                    '&key=' +
                    formKey +
                    '&isAll=' +
                    columnName +
                    '测评报告'
                  "
                >
                  测评报告
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template>
          <h3 class="sub-title">题目得分</h3>
          <form-item-list
            v-if="detailList.length > 0"
            ref="formItemList"
            :form-key="formKey"
            :type="type"
            :data-list="detailList"
          ></form-item-list>
          <el-empty v-else description="暂无数据"></el-empty>
        </template>
        <template v-if="evaluated">
          <h3 class="sub-title">主观评价展示</h3>
          <form-item-text-list
            v-if="textDataList.length > 0"
            ref="formItemTextList"
            :data-list="textDataList"
          ></form-item-text-list>
          <el-empty v-else description="暂无数据"></el-empty>
        </template>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { getRequest } from '@/api/baseRequest'
import FormItemList from '@/views/form/statistics/report/FormItemList.vue'
import FormItemTextList from '@/views/form/statistics/report/FormItemTextList.vue'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import { Loading } from 'element-ui'
import { saveAs } from 'file-saver'
import FileSaver from 'file-saver'
import htmlDocx from 'html-docx-js/dist/html-docx'
import JSZip from 'jszip'
import { GET_EVALUATED_LIST, GET_TEMP_ZIP, SET_EVALUATED_LIST, SET_TEMP_ZIP } from '@/store/mutation-types'

export default {
  name: 'Report',
  components: { FormItemList, FormItemTextList },
  data() {
    return {
      dataList: [],
      type: '',
      reportTitle: '测评报告',
      formKey: '',
      evaluated: '',
      form: {},
      detailList: [],
      textDataList: [],
      isAll: 0,
      reportTypeList: [],
      evaluatedList: [],
      evaluatedName: '',
      showPrint: true
    }
  },
  filters: {
    numFilter(value) {
      // 截取当前数据到小数点后两位
      return parseFloat(value).toFixed(2)
    },
    isHalf() {
      return (this.evaluated.length = 0)
    }
  },
  computed: {
    columnName() {
      if (this.type == 5) {
        return '被评价部门'
      } else if (this.type == 6) {
        return '被评价人'
      } else {
        return '名称'
      }
    }
  },
  created() {
    this.type = this.$route.query.type
    this.formKey = this.$route.query.key
    this.evaluated = this.$route.query.evaluated
    this.reportTypeList = [
      {
        id: 0,
        label: '所有' + this.columnName + '测评报告'
      },
      {
        id: 1,
        label: this.columnName + '测评报告'
      }
    ]
    this.isAll = this.$route.query.isAll || 0
    this.getTextData()
    this.getData()
    this.getEvaluatedList()
    this.$forceUpdate()
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.downloadAll()
      }, 3000)
    })
  },
  methods: {
    downloadAll() {
      if (this.$route.query.downloadAll) {
        let evaluatedList = this.$store.getters[GET_EVALUATED_LIST]
        let index = parseInt(this.$route.query.index)
        this.downloadPDF()
        if (index < evaluatedList.length - 1) {
          this.goNext(index + 1)
        } else {
          let zip = this.$store.getters[GET_TEMP_ZIP]
          setTimeout(() => {
            zip
              .generateAsync({ type: 'blob' })
              .then((content) => {
                FileSaver.saveAs(content, this.form.textName + '.zip')
              })
              .then(() => {
                this.$router.replace({
                  path: '/project/form/statistics',
                  query: {
                    type: this.type,
                    key: this.formKey,
                    activeTab: 'report'
                  }
                })
              })
          }, 2000)
          this.$message.success('下载完成')
        }
      }
    },
    goNext(index) {
      let evaluatedList = this.$store.getters[GET_EVALUATED_LIST]
      this.$router.replace({
        path: '/project/form/statistics',
        query: {
          key: this.formKey,
          type: this.type,
          evaluated: evaluatedList[index].evaluated,
          activeTab: 'report',
          isAll: this.columnName + '测评报告',
          downloadAll: true,
          index: index
        }
      })
    },
    getData() {
      let loadingInstance = Loading.service({ text: '正在生成报告' })
      getRequest('/report/getReport', { formKey: this.formKey, evaluated: this.evaluated })
        .then((res) => {
          if (res.code == 200) {
            this.dataList = res.data.evaluatedScoreDTOList
            if (this.dataList.length > 0) {
              this.evaluatedName = this.dataList[0].evaluatedName
            }
            this.form = res.data.userFormEntity
            this.detailList = res.data.formItemScoreDTOList
            console.log(this.form)
          }
        })
        .finally((res) => {
          loadingInstance.close()
        })
    },
    getTextData() {
      if (!this.evaluated) {
        return
      }
      getRequest('/report/getItemText', { formKey: this.formKey, evaluated: this.evaluated }).then((res) => {
        if (res.code == 200) {
          this.textDataList = res.data
        }
      })
    },
    getEvaluatedList() {
      const _this = this
      getRequest('/form/relationship/listDistinct', { formKey: this.formKey }).then((res) => {
        if (res.code === 200) {
          this.evaluatedList = res.data
          for (let e of this.evaluatedList) {
            if (e.evaluated == this.evaluated) {
              this.evaluated = e.evaluatedName
              this.evaluatedName = e.evaluatedName
            }
          }
          _this.$store.commit(SET_EVALUATED_LIST, res.data)
        }
      })
    },
    handleSelectChange(e) {
      if (e == 1) {
        this.$router.push({
          path: '/project/form/statistics',
          query: {
            key: this.formKey,
            type: this.type,
            evaluated: this.evaluatedList[0].evaluated,
            activeTab: 'report',
            isAll: this.columnName + '测评报告'
          }
        })
      } else {
        this.$router.push({
          path: '/project/form/statistics',
          query: {
            key: this.formKey,
            type: this.type,
            activeTab: 'report',
            isAll: '所有' + this.columnName + '测评报告'
          }
        })
      }
    },
    handleEvaluatedSelect(e) {
      this.$router.push({
        path: '/project/form/statistics',
        query: {
          key: this.formKey,
          type: this.type,
          evaluated: e,
          activeTab: 'report',
          isAll: this.columnName + '测评报告'
        }
      })
    },
    downloadPDF() {
      const element = document.querySelector('#dispatchReportPage')
      const opts = {
        scale: 2, // 缩放比例，提高生成图片清晰度，不推荐太高
        useCORS: true, // 允许加载跨域的图片
        allowTaint: false, // 允许图片跨域，和 useCORS 二者不可共同使用
        tainttest: true, // 检测每张图片已经加载完成
        logging: true, // 日志开关，发布的时候记得改成 false
        dpi: 1200
      }

      html2canvas(element, opts).then((canvas) => {
        const contentWidth = canvas.width
        const contentHeight = canvas.height
        // 一页pdf显示html页面生成的canvas高度;
        const pageHeight = (contentWidth / 592.28) * 841.89
        // 未生成pdf的html页面高度
        let leftHeight = contentHeight
        // 页面偏移
        let position = 0
        // a4纸的尺寸[595.28,841.89]
        const imgWidth = 595.28
        const imgHeight = (592.28 / contentWidth) * contentHeight
        const pageData = canvas.toDataURL('image/jpeg', 1.0)
        // a4纸纵向，一般默认使用；new JsPDF('landscape'); 横向页面
        const PDF = new jsPDF('p', 'pt', 'a4')
        // 当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < pageHeight) {
          // addImage(pageData, 'JPEG', 左，上，宽度，高度)设置
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          // 超过一页时，分页打印（每页高度841.89）
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }
        let fileName = this.evaluated ? this.form.textName + '-' + this.evaluatedName : this.form.textName
        if (this.$route.query.downloadAll) {
          let zip = this.$store.getters[GET_TEMP_ZIP]
          zip.file(fileName + '.pdf', PDF.output('blob'))
          this.$store.commit(SET_TEMP_ZIP, zip)
          /*       if (this.$route.query.index == this.evaluatedList.length -1 ) {
                        zip.generateAsync({type: 'blob'}).then((content) => {
                            FileSaver.saveAs(content, this.form.textName + '.zip')
                        })
                        this.$message.success('下载完成')
                        this.$router.replace({
                            path: '/project/form/statistics',
                            query:{
                                type:this.type,
                                key:this.formKey,
                                activeTab:'report'
                            }
                        })
                    } else {
                        this.$store.commit(SET_TEMP_ZIP, zip)
                    }*/
        } else {
          PDF.save(fileName + '.pdf')
        }
      })
    },
    exportPDF() {
      console.log('exportPDF...start')
      const _this = this
      this.$nextTick(() => {
        // 生成的pdf只有页面窗口可见的区域，有滚动条的下面没有生成出来，需在生成PDF前，改overflow属性auto为visible
        // 获取dom高度、宽度
        var shareContent = document.querySelector('#dispatchReportPage')
        var width = shareContent.offsetWidth / 4
        var height = shareContent.offsetHeight / 4
        let _this = this
        // eslint-disable-next-line
        let loadingInstance = Loading.service({ text: '正在导出，请稍等' })
        html2canvas(document.getElementById('dispatchReportPage'), {
          dpi: 1200,
          background: '#ffffff',
          scale: 2,
          // scrolly: 0,
          // width:eleW,//生成后的宽度
          // height:eleH,//生成后的高度
          // scrollx: -10,
          useCORS: true //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。

          // backgroundColor: null //避免图片有白色边框
        }).then((canvas) => {
          var context = canvas.getContext('2d')
          context.mozImageSmoothingEnabled = false
          context.webkitImageSmoothingEnabled = false
          context.msImageSmoothingEnabled = false
          context.imageSmoothingEnabled = false
          var pageData = canvas.toDataURL('image/jpeg', 1.0)
          var img = new Image()
          img.src = pageData
          img.onload = () => {
            // 获取dom高度、宽度
            img.width = img.width / 2
            img.height = img.height / 2
            img.style.transform = 'scale(0.5)'
            if (width > height) {
              // 此可以根据打印的大小进行自动调节
              // eslint-disable-next-line
              var pdf = new jsPDF('l', 'mm', [width * 0.505, height * 0.545])
              // var pdf = new jsPDF('l', 'mm', [width, height])
            } else {
              // eslint-disable-next-line
              var pdf = new jsPDF('p', 'mm', [width * 0.505, height * 0.545])
              // var pdf = new jsPDF('p', 'mm', [width, height])
            }
            pdf.addImage(pageData, 'jpeg', 0, 0, width * 0.505, height * 0.545)
            // pdf.addImage(pageData, 'jpeg', 0, 0, width, height)
            let fileName = this.evaluated ? this.form.textName + '-' + this.evaluatedName : this.form.textName
            pdf.save(fileName + '.pdf')
            loadingInstance.close()
            console.log('exportPDF...end')
            if (this.$route.query.downloadAll) {
              window.close()
            }
            return pdf
          }
        })
      })
    },
    exportDoc() {
      let fileName = this.evaluated ? this.form.textName + '-' + this.evaluatedName : this.form.textName
      saveAs(
        htmlDocx.asBlob(document.querySelector('#dispatchReportPage').innerHTML, { orientation: 'landscape' }),
        fileName + '.doc'
      )
    }
  }
}
</script>

<style scoped>
.header-bg {
  background-image: url('~@/assets/images/bg-baogao@2x.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.header-line-height {
  height: 400px !important;
  display: flex;
}

.header-title {
  text-align: center;
  margin: unset;
  color: white;
  /*line-height: 300px;*/
  font-size: 40px;
  margin-top: 20%;
}

.table-header {
  background: grey;
  font-size: 20px;
  font-weight: bolder;
}

.sub-title {
  border-left: 6px solid black;
  padding-left: 10px;
  font-weight: bold;
}

.half {
  /*float: left;*/
  width: 50%;
}

.red {
  color: #ff6161;
}

.green {
  color: #39b895;
}

.row-font {
  font-size: 40px;
}
</style>
